const { app, BrowserWindow } = require('electron');
const path = require('path');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
    backgroundColor: '#ffffff',
    titleBarStyle: 'default',
  });

  // 开发模式下加载 webpack dev server
  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
  if (isDev) {
    mainWindow.loadURL('http://localhost:3000');
    mainWindow.webContents.openDevTools();
  } else {
    // 生产模式加载打包后的文件
    mainWindow.loadFile(path.join(__dirname, 'dist', 'index.html'));
  }
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// IPC 处理程序（从原来的 main.js 移动过来）
const { ipcMain } = require('electron');
const axios = require('axios');

const API_BASE_URL = 'http://localhost:8080/api';

ipcMain.handle('search-word', async (event, word) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dictionary/search`, {
      params: { word }
    });
    return { success: true, data: response.data };
  } catch (error) {
    console.error('搜索失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('search-fuzzy', async (event, keyword) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dictionary/search/fuzzy`, {
      params: { keyword }
    });
    return { success: true, data: response.data };
  } catch (error) {
    console.error('模糊搜索失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('get-sources', async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/sources`);
    return { success: true, data: response.data };
  } catch (error) {
    console.error('获取词典源失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('download-source', async (event, sourceName) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/sources/${sourceName}/download`);
    return { success: true, data: response.data };
  } catch (error) {
    console.error('下载失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('get-download-tasks', async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dictionary/download/tasks`);
    return { success: true, data: response.data };
  } catch (error) {
    console.error('获取下载任务失败:', error);
    return { success: false, error: error.message };
  }
});

ipcMain.handle('get-stats', async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dictionary/stats`);
    return { success: true, data: response.data };
  } catch (error) {
    console.error('获取统计信息失败:', error);
    return { success: false, error: error.message };
  }
});
